package com.song.exception;

import com.song.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        log.error("错误信息:{}",e.getMessage());
        //根据错误信息返回具体的错误信息
        String errMsg = e.getMessage();
        String [] errDetailArr  = errMsg.substring(errMsg.lastIndexOf("Duplicate entry ")).split(" ");
        //errDetailArr =  "Duplicate entry '张三' for key 'emp.username'"
        String key = errDetailArr[5].substring(errDetailArr[5].indexOf(".") + 1);//emp.username -> username
        String value = errDetailArr[2];//张三
        return Result.error("操作失败，" + key + ":" + value + ", 已存在");

    }
}
